//
//  View.swift
//  Box
//
//  Created by mn on 2025/3/30.
//

import UIKit

private var TapActionKey: UInt8 = 0

extension UIView {
    typealias TapAction = () -> Void

    private var tapAction: TapAction? {
        get {
            return objc_getAssociatedObject(self, &TapActionKey) as? TapAction
        }
        set {
            objc_setAssociatedObject(self, &TapActionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func addTapAction(action: @escaping TapAction) {
        tapAction = action
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAction))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tapGesture)
    }

    @objc private func handleTapAction() {
        tapAction?()
    }

    func findViewController() -> UIViewController? {
       var responder: UIResponder? = self
       while let nextResponder = responder?.next {
           responder = nextResponder
           if let viewController = responder as? UIViewController {
               return viewController
           }
       }
       return nil
   }
    
}
